<!--
 * @Author: ybf
 * @Date: 2023-02-21 15:31:51
 * @LastEditTime: 2023-12-04 17:56:22
 * @Description: 描述
 * Copyright (c) 2023 by 慧能分享, All Rights Reserved.
-->
<template>
    <div class="electricityMeter">
        <!-- <nu-col :span="24" style="height:calc(130px - 20px);">
                                            <nutbTitle title="电度量"></nutbTitle> -->
        <!-- <el-radio-group class="el_radioView" v-model="formData.mesaType" @input="relatedNameInput"
            style="margin-left: 28px">
            <el-radio-button v-for="item in measureTypeList" :key="item.dictActualValue" :label="item.dictActualValue">
                {{ item.dictName }}
            </el-radio-button>
        </el-radio-group> -->
        <NuVerifyForm :model="formData" ref="formData" label-width="100px" class="searchForm" @searchForm="searchForm"
            :buttons="fyButtons">
            <NuformItem label="计量点名称" prop="meterName" width="auto">
                <el-autocomplete v-model="formData.meterName" :fetch-suggestions="querySearchAsync" placeholder="请输入计量点名称"
                    @select="handleSelect"></el-autocomplete>
            </NuformItem>
            <NuformItem label="电度量名称" prop="pointName" width="auto">
                <nu-input type="text" v-model="formData.pointName" size="middle" placeholder="请输入电度量名称"></nu-input>
            </NuformItem>
            <div class="btnBox">
                <nu-button type="primary" class="searchButton" @click="searchTable">查询</nu-button>
                <nu-button class="searchButton" @click="clearParams">清除</nu-button>
            </div>
        </NuVerifyForm>
        <div class="line"></div>
        <div style="height:35px;position: relative;padding: 0 10px;" class="renovateTime">
            <nu-button class="searchButton" @click="addTable">单点新增</nu-button>
            <nu-button class="searchButton" @click="batchAddTable">批量新增</nu-button>
            <nu-button class="searchButton" @click="importTable">导入</nu-button>
        </div>
        <!-- </nu-col> -->
        <!-- <nu-col :span="24" style="height: calc(100% - 130px - 20px);">
            <nutbTitle title="点表列表"></nutbTitle> -->
        <!-- <div class="btnBox2">
            <nu-button type="primary" class="searchButton" size="mini" @click="copyRow">复制</nu-button>
            <nu-button type="primary" class="searchButton" size="mini" @click="stickRow">粘贴</nu-button>
            </div> -->
        <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="options"
            :operates="operates(this)" border :pagination="pagination" @handleSizeChange="handleSizeChange"
            @handleChangePage="handleChangePage" @handleCurrentChange="handleCurrentChange">
        </NuTableList>
        <!-- </nu-col> -->
        <!-- 单点新增 -->
        <nu-dialog :title="dialogTitle" :visible.sync="dialogShow" width="42%" center :close-on-click-modal="false"
            top="5vh" :modal-append-to-body="false" @close="diaClose">
            <div class="dialogHeaderSearch">
                <NuVerifyForm :model="dialogFormData" ref="dialogFormData" label-width="120px" class="submitForm"
                    @submitForm="diaSubmitForm" :buttons="fyButtons">
                    <NuformItem label="厂站名称" prop="plantId" width="46%" :rules="[{ required: true, message: '厂站名称不能为空' }]">
                        <!-- <nu-input type="text" v-model="dialogFormData.plantName" size="middle" :disabled="false"
                                                placeholder="请输入"></nu-input> -->
                        <nu-select class="searchSelect" :filterable="true" :list="plantNameList" type="text"
                            v-model="dialogFormData.plantId" autocomplete="off"
                            style="width: calc(100% - 5px);margin-left: 2px;" :disabled="dialogFormDisabled"
                            placeholder="请选择" @change="plantNameChange">
                        </nu-select>
                    </NuformItem>
                    <NuformItem label="计量点名称" prop="meterName" width="46%"
                        :rules="[{ required: true, message: '计量点名称不能为空' }]">
                        <el-autocomplete v-model="dialogFormData.meterName" :fetch-suggestions="querySearchMetric"
                            placeholder="请选择" @select="handleSelect" style="width:100%"></el-autocomplete>
                    </NuformItem>
                    <NuformItem label="电度量名称" prop="pointName" width="46%"
                        :rules="[{ required: true, message: '电度量名称不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.pointName" size="middle"
                            :disabled="dialogFormDisabled" placeholder="请输入"></nu-input>
                    </NuformItem>
                    <NuformItem label="点号" prop="ioa" width="46%" :rules="[{ required: true, message: '点号不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.ioa" size="middle" :disabled="dialogFormDisabled"
                            placeholder="请输入"></nu-input>
                    </NuformItem>
                    <!-- <NuformItem label="点号" prop="ioa" width="46%" :rules="[{ required: true, message: '点号不能为空' }]">
                        <nu-input type="number" v-model="dialogFormData.ioa" size="middle" :disabled="dialogFormDisabled"
                            placeholder="请输入"></nu-input>
                    </NuformItem> -->
                    <NuformItem label="单位" prop="unit" width="46%" :rules="[{ required: true, message: '单位不能为空' }]">
                        <nu-select class="searchSelect" :filterable="true" :list="unitList" type="text"
                            v-model="dialogFormData.unit" autocomplete="off"
                            style="width: calc(100% - 5px);margin-left: 2px;" :disabled="dialogFormDisabled"
                            placeholder="请选择">
                        </nu-select>
                    </NuformItem>
                    <!-- <NuformItem label="当前值" prop="currVal" width="46%" :rules="[{ required: true, message: '当前值不能为空' }]">
                        <nu-input type="number" v-model="dialogFormData.currVal" size="middle"
                            :disabled="dialogFormDisabled" placeholder="请输入"></nu-input>
                    </NuformItem> -->
                    <NuformItem label="系数" prop="coeff" width="46%" :rules="[{ required: true, message: '系数不能为空' }]">
                        <nu-input type="number" v-model="dialogFormData.coeff" size="middle" :disabled="dialogFormDisabled"
                            @input="(value) => { if (value.indexOf('.') > 0) { dialogFormData.coeff = value.slice(0, value.indexOf('.') + 9) } }"
                            @blur="coefBlur($event, 8)" placeholder="请输入"></nu-input>
                    </NuformItem>
                    <!-- <NuformItem label="小数位数" prop="pointDot" width="46%" :rules="[{ required: true, message: '小数位数不能为空' }]">
                        <nu-select class="searchSelect" :filterable="true" :list="decList" type="text"
                            v-model="dialogFormData.pointDot" autocomplete="off"
                            style="width: calc(100% - 5px);margin-left: 2px;" :disabled="dialogFormDisabled"
                            placeholder="请选择">
                        </nu-select>
                    </NuformItem> -->
                    <NuformItem label="偏移量" prop="offsetVal" width="46%" :rules="[{ required: true, message: '偏移量不能为空' }]">
                        <nu-input type="number" v-model="dialogFormData.offsetVal" size="middle"
                            :disabled="dialogFormDisabled" placeholder="请输入"></nu-input>
                    </NuformItem>
                    <NuformItem label="是否统计" prop="isStatis" width="46%" :rules="[{ required: true, message: '是否统计不能为空' }]">
                        <nu-radioButton :group="groupList" v-model="dialogFormData.isStatis"></nu-radioButton>
                    </NuformItem>
                    <!-- <NuformItem label="采样周期" prop="samplePeriod" width="46%"
                        :rules="[{ required: true, message: '采样周期不能为空' }]">
                        <nu-select class="searchSelect" :filterable="true" :list="periodList" type="text"
                            v-model="dialogFormData.samplePeriod" autocomplete="off"
                            style="width: calc(100% - 5px);margin-left: 2px;" :disabled="dialogFormDisabled"
                            placeholder="请选择">
                        </nu-select>
                    </NuformItem> -->
                </NuVerifyForm>
                <nu-button class="dialogSearchButton" type="primary" @click="diaClose">取消</nu-button>
                <nu-button class="dialogSearchButton" type="primary" @click="diaSave"
                    v-if="dialogTitle == '编辑'">确定</nu-button>
                <nu-button class="dialogSearchButton" type="primary" @click="diaSave"
                    v-if="dialogTitle == '新增'">确定</nu-button>
            </div>
        </nu-dialog>
        <!-- 批量新增 -->
        <nu-dialog :title="dialogBatchTitle" :visible.sync="dialogBatchShow" width="70%" center
            :close-on-click-modal="false" top="5vh" :modal-append-to-body="false" @close="diaBatchClose">
            <div class="dialogHeaderSearch batch">
                <NuTableList :showFilter="false" :columns="batchColumns" :dataSource="batchDataSource" style="width: 100%;"
                    :options="options" border>
                </NuTableList>
                <nu-button class="dialogSearchButton" type="primary" @click="diaBatchSave">保存</nu-button>
            </div>
        </nu-dialog>
        <!-- 导入 -->
        <nu-dialog :title="upload.title" :visible.sync="upload.open" width="550px" center :close-on-click-modal="false"
            top="5vh" :modal-append-to-body="false">
            <div class="upload_des">
                <span>请下载模板文件，并根据模板中的样式要求，填写信息</span>
                <el-link type="primary" :underline="false"
                    style="font-size:12px;vertical-align: baseline;color:rgba(72, 118, 255, 1)"
                    @click="importTemplate">下载导入模板.xlsx</el-link>
            </div>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                :on-change="handleChange" :auto-upload="false" drag :data="upload.data" name="file"
                style="width:100%;overflow: hidden;">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>1.后缀为xls或xlsx；</span>
                    <span>2.文件大小不超过5M；</span>
                    <span>3.若有多个sheet页，默认读取第一个</span>

                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <nu-button type="primary" @click="submitFileForm">确 定</nu-button>
                <nu-button @click="closeFileForm">取 消</nu-button>
            </div>
        </nu-dialog>
    </div>
</template>
    
<script>
import nuCol from "@/components/base/col.vue"
import nutbTitle from "@/components/base/tableTitle.vue"
import NuVerifyForm from "@/components/verify-form"
import NuformItem from "@/components/verify-form/form-item.vue"
import nuInput from "@/components/base/input"
import nuSelect from "@/components/base/select"
import nuButton from "@/components/base/button"
import NuTableList from "@/components/tableList/TableFormList"
import nuDialog from "@/components/base/dialog"
import nuRadio from "@/components/base/radio"
import nuRadioButton from "@/components/base/radio-button"
import axios from 'axios'
import { saveAs } from 'file-saver'
const operates = that => [
    {
        label: '编辑',
        icon: '',
        width: '50px',
        isShow: row => {
            return true;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            that.openEdit(row);
        },
    },
    // {
    //   isShow: row => {
    //     return false;
    //   },
    // },
    {
        label: '',
        icon: '',
        width: '50px',
        isShow: row => {
            return false;
        },
        disabled: row => {
            return false;
        },
        method: row => {
        },
        render: (h, params) => {
            return h(nuButton, {
                props: {
                    type: 'text'
                },
                class: 'tableOperateBtn',
                on: {
                    click: () => {
                        that.forbidden(params.row);
                    },
                }
            }, params.row.isStatis == 1 ? '禁用' : '重新启用');
        },
    },
    {
        label: '删除',
        icon: '',
        width: '50px',
        isShow: row => {
            return row.isStatis == 0 ? true : false;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            that.tbRowdetele(row);
        },
    },
];
import { getToken } from "@/utils/auth";
export default {
    name: "electricityMeter",
    components: { nuCol, nutbTitle, NuVerifyForm, NuformItem, nuInput, nuSelect, nuButton, NuTableList, nuDialog, nuRadio, nuRadioButton },
    data() {
        return {
            formData: {
                meterName: '',
                pointName: '',
                mesaType: '201'
            },
            dialogFormData: {
                plantName: '',
                plantId: '',
                meterName: '',
                meterId: '',
                pointName: '',
                unit: '',
                coeff: '',
                pointDot: '',
                samplePeriod: '',
                isStatis: '是',
                ioa: '',
                offsetVal: ''
            },
            fyButtons: [],
            operates,
            currentRow: null,
            pagination: {
                pageSize: 20,
                total: 0,
                pageNum: 1,
            },
            dialogTitle: '',
            dialogShow: false,
            dialogBatchTitle: '',
            dialogBatchShow: false,
            groupList: ['是', '否'],
            unitList: [{ label: 'kW', value: 'kW' }, { label: 'W', value: 'W' }, { label: 'mW', value: 'mW' }],
            decList: [{ label: '1', value: '1' }, { label: '2', value: '2' }, { label: '3', value: '3' }, { label: '4', value: '4' }],
            periodList: [{ label: '15min', value: '15min' }, { label: '5min', value: '5min' }],
            measureTypeList: [{ dictName: '遥测', dictActualValue: '201' }, { dictName: '遥信', dictActualValue: '202' }],
            columns: [
                {
                    label: '序号',
                    prop: 'ranking',
                    width: '70px',
                    render: (h, params) => {
                        return h('span', params.index + 1 + (this.pagination.pageNum - 1) * this.pagination.pageSize);
                    },
                },
                {
                    label: '厂站名称',
                    prop: 'plantName',
                },
                {
                    label: '计量点名称',
                    prop: 'meterName',
                },
                {
                    label: '电度量名称',
                    prop: 'pointName',
                },
                {
                    label: '点号',
                    prop: 'ioa',
                },
                {
                    label: '单位',
                    prop: 'unit',
                },
                {
                    label: '是否统计',
                    prop: 'isStatis',
                    render: (h, params) => {
                        return h('span', params.row.isStatis == 1 ? '是' : '否');
                    },
                },
                // {
                //     label: '当前值',
                //     prop: 'currVal',
                // },
                {
                    label: '偏移量',
                    prop: 'offsetVal',
                },
                {
                    label: '系数',
                    prop: 'coeff',
                },
                // {
                //     label: '小数位数',
                //     prop: 'pointDot',
                // },
                // {
                //     label: '采样频率',
                //     prop: 'samplePeriod',
                // }
            ],
            batchColumns: [
                {
                    label: '序号',
                    prop: 'ranking',
                    width: '70px',
                    render: (h, params) => {
                        return h('span', params.index + 1);
                    },
                },
                {
                    label: '厂站名称',
                    prop: 'plantId',
                    width: '150px',
                    render: (h, params) => {
                        return h(nuSelect, {
                            attrs: {
                                value: params.row.plantId,
                                placeholder: '请选择',
                                autocomplete: "off",
                                type: "text",
                                clearable: true
                            },
                            props: {
                                list: this.plantNameList,
                            },
                            style: 'width:100%',
                            class: 'searchSelect',
                            on: {
                                change: val => {
                                    if (val) {
                                        params.row.plantId = val
                                        let obj = this.plantNameList.filter(item => { return item.value == val })[0]
                                        params.row.plantName = obj.label
                                    }
                                },
                                clear: val => {
                                    params.row.plantId = ''
                                    params.row.plantName = ''
                                }
                            },
                        });
                    },
                },
                {
                    label: '计量点名称',
                    prop: 'meterName',
                    width: 170,
                    render: (h, params) => {
                        return h('el-autocomplete', {
                            attrs: {
                                value: params.row.meterName,
                                clearable: true
                            },
                            props: {
                                'fetch-suggestions': (queryString, cb) => this.querySearchBatch(queryString, cb, params.row.plantId),
                                placeholder: '请选择',
                            },
                            style: 'width:100%',
                            on: {
                                select: val => {
                                    params.row.meterName = val.value
                                    params.row.meterId = this.meteringPointData.filter(item => item.name == val.value)?.[0]?.id
                                },
                                clear: val => {
                                    params.row.meterName = ''
                                    params.row.meterId = ''
                                },
                                input: val => {
                                    params.row.meterName = val
                                    if (val) {
                                        params.row.meterId = this.meteringPointData.filter(item => item.name == val)?.[0]?.id
                                    }
                                }
                            },
                        });
                    },
                },
                {
                    label: '电度量名称',
                    prop: 'pointName',
                    render: (h, params) => {
                        return h(nuInput, {
                            attrs: {
                                value: params.row.pointName,
                                placeholder: '请输入',
                                type: 'text',
                            },
                            props: {
                                size: "middle",
                            },
                            style: 'width:100%',
                            on: {
                                input: val => {
                                    params.row.pointName = val
                                }
                            },
                        });
                    },
                },
                {
                    label: '点号',
                    prop: 'ioa',
                    width: 130,
                    render: (h, params) => {
                        return h(nuInput, {
                            attrs: {
                                value: params.row.ioa,
                                placeholder: '请输入',
                                type: 'text',
                            },
                            props: {
                                size: "middle",
                            },
                            style: 'width:100%',
                            on: {
                                input: val => {
                                    params.row.ioa = val
                                }
                            },
                        });
                    },
                },
                {
                    label: '单位',
                    prop: 'unit',
                    width: 130,
                    render: (h, params) => {
                        return h(nuSelect, {
                            attrs: {
                                value: params.row.unit,
                                placeholder: '请选择',
                                autocomplete: "off",
                                type: "text",
                            },
                            props: {
                                list: this.unitList,
                            },
                            style: 'width:100%',
                            class: 'searchSelect',
                            on: {
                                change: val => {
                                    params.row.unit = val
                                }
                            },
                        });
                    },
                },
                // {
                //     label: '当前值',
                //     prop: 'currVal',
                //     render: (h, params) => {
                //         return h(nuInput, {
                //             attrs: {
                //                 value: params.row.currVal,
                //                 placeholder: '请输入',
                //                 type: "text",
                //             },
                //             props: {
                //                 size: "middle"
                //             },
                //             style: 'width:100%',
                //             on: {
                //                 input: val => {
                //                     params.row.currVal = val
                //                 }
                //             },
                //         });
                //     },
                // },
                {
                    label: '偏移量',
                    prop: 'offsetVal',
                    width: 130,
                    render: (h, params) => {
                        return h(nuInput, {
                            attrs: {
                                value: params.row.offsetVal,
                                placeholder: '请输入',
                                type: "text",
                            },
                            props: {
                                size: "middle"
                            },
                            style: 'width:100%',
                            on: {
                                input: val => {
                                    params.row.offsetVal = val
                                }
                            },
                        });
                    },
                },
                {
                    label: '系数',
                    prop: 'coeff',
                    width: 130,
                    render: (h, params) => {
                        return h(nuInput, {
                            attrs: {
                                value: params.row.coeff,
                                placeholder: '请输入',
                                type: "text",
                            },
                            props: {
                                size: "middle"
                            },
                            style: 'width:100%',
                            on: {
                                input: val => {
                                    if (val) {
                                        params.row.coeff = val
                                        if (val.indexOf('.') > 0) { params.row.coeff = val.slice(0, val.indexOf('.') + 9) }
                                    } else {
                                        params.row.coeff = ''
                                    }

                                },
                                blur: $event => this.coefBlur($event, 8)
                            },
                        });
                    },
                },
                // {
                //     label: '小数位数',
                //     prop: 'pointDot',
                //     width: 90,
                //     render: (h, params) => {
                //         return h(nuSelect, {
                //             attrs: {
                //                 value: params.row.pointDot,
                //                 placeholder: '请选择',
                //                 autocomplete: "off",
                //                 type: "text",
                //             },
                //             props: {
                //                 list: this.decList,
                //             },
                //             style: 'width:100%',
                //             class: 'searchSelect',
                //             on: {
                //                 change: val => {
                //                     params.row.pointDot = val
                //                 }
                //             },
                //         });
                //     },
                // },
                // {
                //     label: '采样频率',
                //     prop: 'samplePeriod',
                //     width: 90,
                //     render: (h, params) => {
                //         return h(nuSelect, {
                //             attrs: {
                //                 value: params.row.samplePeriod,
                //                 placeholder: '请选择',
                //                 autocomplete: "off",
                //                 type: "text",
                //             },
                //             props: {
                //                 list: this.periodList,
                //             },
                //             style: 'width:100%',
                //             class: 'searchSelect',
                //             on: {
                //                 change: val => {
                //                     params.row.samplePeriod = val
                //                 }
                //             },
                //         });
                //     },
                // },
                {
                    label: '是否统计',
                    prop: 'isStatis',
                    width: 130,
                    render: (h, params) => {
                        return h(nuRadioButton, {
                            attrs: {
                                value: params.row.isStatis,
                                group: this.groupList,
                                size: "mini"
                            },
                            props: {},
                            style: 'width:100%',
                            on: {
                                input: val => {
                                    params.row.isStatis = val
                                }
                            },
                        });
                    },
                },
            ],
            dataSource: [],
            batchDataSource: [],
            options: {
                'default-expand-all': true,
                'element-loading-background': 'rgba(225,239,242)',
                'element-loading-text': '数据正在加载中',
                'row-key': 'pid',
                'header-cell-style': {
                    background: 'rgba(105, 159, 209, 0.7)',
                    color: '#fff',
                    fontWeight: 'bold',
                    fontsize: '16px',
                },
                height: 'calc(100vh - 340px)',
                props: {
                    // fixed: 'right'
                }
            },
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_SCADA + window.api.importElectricityData,
                // 上传时附带的额外参数
                data: { id: '' }
            },
            restaurants: [],
            state: '',
            timeout: null,
            plantNameList: [],
            meteringPointData: []
        };
    },
    computed: {
        dialogFormDisabled() {
            return this.dialogTitle == '详情'
        }
    },
    created() {
    },
    mounted() {
        this.loadAll()
        this.geElectricityMeterData();
        this.getStationTable()
        this.getMetricPointData()
    },
    methods: {
        /**
         * 查询
         */
        searchTable() {
            this.$refs['formData'].searchForm('form');
        },
        /**
         * form组件内置查询事件
         */
        searchForm(val) {
            if (val) {
                this.geElectricityMeterData();
            }
        },
        /**
         * 清除数据
         */
        clearParams() {
            this.resetForm('formData')
            this.formData.mesaType = '201'
        },
        /**
         * 类型change事件
         */
        typrChange() {

        },
        plantNameChange(val) {
            let obj = this.plantNameList.filter(item => { return item.value == val })[0]
            this.dialogFormData.plantName = obj.label
        },
        /**
         * 系数验证小数点4位，不足补齐0
         * @param {*} e 
         * @param {*} n 
         */
        coefBlur(e, n) {
            if (e.target.value) {
                n = n ? parseInt(n) : 0;
                if (n <= 0) {
                    return Math.round(e.target.value);
                }
                let str = e.target.value + ''
                let length = str.split('.')[1]?.length
                if (length && length <= n) {
                    for (let i = 0; i < n - length; i++) {
                        str += "0";
                    }
                    e.target.value = str
                } else {
                    e.target.value = Number(e.target.value).toFixed(n); //补足位数
                }
                // e.target.value = Math.round(e.target.value * Math.pow(10, n)) / Math.pow(10, n); //四舍五入
                // e.target.value = Number(e.target.value).toFixed(n); //补足位数
            }
        },
        /**
         * 关联input
         */
        relatedNameInput(val) {
            this.radioObj = false
            this.formData.mesaType = val;
            let p = JSON.parse(JSON.stringify(this.pagination))
            this.pagination = null
            this.$nextTick(() => {
                p.pageNum = 1;
                p.currentPage = 1;
                this.pagination = p
                this.geElectricityMeterData();
            })
        },
        /**
         * 新增
         */
        addTable() {
            this.dialogTitle = '新增'
            this.dialogFormData.plantName = ''
            this.dialogFormData.plantId = ''
            this.dialogFormData.unit = "MW"
            this.dialogFormData.isStatis = '是'
            this.dialogFormData.pointDot = "4"
            this.dialogFormData.samplePeriod = "15min"
            this.dialogShow = true
        },
        /**
         * 批量新增
         */
        batchAddTable() {
            this.dialogBatchShow = true
            this.dialogBatchTitle = '批量新增'
            this.batchDataSource = this.generateCycleData()
        },
        /** 下载模板操作 */
        importTemplate() {
            axios.get('/electricityMeterTemplate.xlsx', {
                responseType: 'blob',
            }).then(response => {
                const blob = new Blob([response.data])
                saveAs(blob, '电度量配置导入模板表.xlsx')
                // const url = window.URL.createObjectURL(new Blob([response.data]));
                // const link = document.createElement('a');
                // let fname = '模板.xls';
                // link.href = url;
                // link.setAttribute('download', fname);
                // document.body.appendChild(link);
                // link.click();
            }).catch(error => {
                console.log('error:' + JSON.stringify(error))
            });
        },
        /**
         * 导入
         */
        importTable() {
            this.upload.title = "导入";
            this.upload.open = true;
        },
        /**
         * 每页条数变化事件
         */
        handleSizeChange(val) {
            this.pagination.pageNum = 1;
            this.pagination.pageSize = val;
            this.geElectricityMeterData();
        },
        /**
         * 改变分页触发事件
         */
        handleChangePage(val) {
            this.pagination.pageNum = val;
            this.geElectricityMeterData();
        },
        /**
         * 表格-编辑
         */
        openEdit(row) {
            this.dialogTitle = '编辑'
            Object.assign(this.dialogFormData, row)
            this.dialogFormData.isStatis = row.isStatis == 1 ? '是' : '否'
            this.dialogShow = true
        },
        /**
         * 表格-详情
         */
        openDetail(row) {
            this.dialogTitle = '详情'
            Object.assign(this.dialogFormData, row)
            this.dialogShow = true
        },
        /**
         * 表格-禁用
         */
        forbidden(row) {
            // 禁用状态下调用重启
            if (row.isStatis == 0) {
                this.$confirm('是否重新启用该电度量配置?', '确认重启', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // this.forbiddenMeteringPointTableData(row)
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消重启'
                    });
                });
                // 
            } else if (row.isStatis == 1) {
                this.$confirm('是否禁用该电度量?', '确认禁用', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // this.forbiddenMeteringPointTableData(row)
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消禁用'
                    });
                });
            }

        },
        /**
         * 返回输入建议的方法
         * @param {*} queryString 
         * @param {*} cb 
         */
        querySearchAsync(queryString, cb) {
            var restaurants = this.restaurants;
            var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
            cb(results);
        },
        /**
         * 单点新增-根据厂站返回输入计量点数据
         * @param {*} queryString 
         * @param {*} cb 
         */
        async querySearchMetric(queryString, cb) {
            let d = await this.getMetricPointData(this.dialogFormData.plantId)
            var restaurants = d.map(item => { return { value: item.meterName } })
            var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
            cb(results);
        },
        /**
         * 批量新增-根据厂站返回输入计量点数据
         * @param {*} queryString 
         * @param {*} cb 
         */
        async querySearchBatch(queryString, cb, id) {
            let d = await this.getMetricPointData(id)
            var restaurants = d.map(item => { return { value: item.meterName } })
            var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
            cb(results);
        },
        /**
         * 过滤数据
         * @param {*} queryString 
         */
        createStateFilter(queryString) {
            return (state) => {
                return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        /**
         * 点击选中建议项时触发
         * @param {*} item 
         */
        handleSelect(item) {
            console.log(item);
        },
        /**
         * 动态生成批量新增数据
         */
        generateCycleData() {
            let data = [];
            Array.from({ length: 10 }).forEach((item, i) => {
                data.push({
                    plantName: '',
                    plantId: '',
                    pointName: '',
                    unit: "MW",
                    coeff: '',
                    pointDot: "4",
                    samplePeriod: "15min",
                    isStatis: '是',
                    meterName: '',
                    meterId: '',
                    ioa: '',
                    offsetVal: ''
                });
            });
            return data;
        },
        /**
         * 表格-删除
         */
        tbRowdetele(row) {
            this.$confirm('确定要删除电度量【' + row.pointName + '】吗？', '确认删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delElectricityMeter(row)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        /**
         * dialogFormData组件内置提交事件
         */
        diaSubmitForm(val) {
            if (val) {
                if (this.dialogTitle == '编辑') {
                    this.editElectricityMeterData()
                } else if (this.dialogTitle == '新增') {
                    this.addElectricityMeterData()
                }
            }
        },
        /**
         * 弹窗-单点新增-保存
         */
        diaSave() {
            this.$refs['dialogFormData'].submitForm('form');
        },
        /**
         * 弹窗-单点新增-关闭
         */
        diaClose() {
            this.dialogShow = false
            this.dialogBatchShow = false
            this.resetForm('dialogFormData')
        },
        /**
         * 重置表单
         */
        resetForm(formName) {
            this.$refs[formName].resetForm('form');
            for (let k in this[formName]) {
                if (Object.prototype.toString.call(this[formName][k]) == "[object String]") {
                    this[formName][k] = ''
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Array]") {
                    this[formName][k] = []
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Number]") {
                    this[formName][k] = ''
                }
            }
        },
        /**
         * 弹窗-批量新增-保存
         */
        diaBatchSave() {
            let data = []
            let pass = true
            this.batchDataSource.forEach(item => {
                let flag = false
                for (let k in item) {
                    if (k != 'unit' && k != 'pointDot' && k != 'samplePeriod' && k != 'isStatis') {
                        if (item[k]) {
                            flag = true
                        }
                    }
                }
                if (flag) {
                    let complete = true
                    for (let k in item) {
                        if (!item[k]) {
                            complete = false
                        }
                    }
                    if (complete) {
                        data.push(item)
                    } else {
                        pass = false
                    }
                }
            })
            if (pass) {
                if (!data.length) {
                    this.$message({
                        message: '请先配置信息',
                        type: 'info'
                    })
                    return false
                }
                this.batchAddElectricityMeterData(data)
            } else {
                this.$message({
                    message: '请将信息输入完整',
                    type: 'info'
                })
            }
        },
        /**
         * 弹窗-批量新增-关闭
         */
        diaBatchClose() {
            this.dialogBatchShow = false
        },
        /**
         * 获取表格数据
         */
        geElectricityMeterData() {
            let postData = {
                ...this.formData,
                ...this.pagination,
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpGet(window.api.getElectricityMeter, postData).then(res => {
                if (res.code == 200) {
                    this.pagination.total = res.total;
                    this.dataSource = res.rows
                    this.diaClose()
                } else {
                }
            }).catch(err => {

            });
        },
        /**
         * 单选
         */
        handleCurrentChange(val) {
            this.currentRow = val
            // console.log(this.currentRow)
        },
        /**
         * 复制
         */
        copyRow() {
            // this.dataSource.push(this.currentRow)
        },
        /**
         * 粘贴
         */
        stickRow() {

        },
        /**
         * 编辑接口
         */
        editElectricityMeterData() {
            this.dialogFormData.meterId = this.meteringPointData.filter(item => item.name == this.dialogFormData.meterName)?.[0]?.id
            this.dialogFormData.isStatis = this.dialogFormData.isStatis == '是' ? 1 : 0
            let postData = {
                ...this.dialogFormData,
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpPost(window.api.editElectricityMeter, postData).then(res => {
                if (res.code == 200) {
                    this.$message({
                        message: res.msg,
                        type: 'success'
                    })
                    this.geElectricityMeterData()
                } else {
                }
            }).catch(err => {

            });
        },
        /**
         * 删除表格数据
         */
        delElectricityMeter(row) {
            let postData = {
                ids: [row.id]
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpPost(window.api.delElectricityMeter, postData).then(res => {
                if (res.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.geElectricityMeterData()
                } else {
                    this.$message({
                        type: 'info',
                        message: res.msg
                    });
                }
            }).catch(err => {

            });
        },
        /**
         * 新增接口
         */
        addElectricityMeterData() {
            this.dialogFormData.meterId = this.meteringPointData.filter(item => item.name == this.dialogFormData.meterName)?.[0]?.id
            this.dialogFormData.isStatis = this.dialogFormData.isStatis == '是' ? 1 : 0
            let postData = {
                ...this.dialogFormData,
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpPost(window.api.addElectricityMeter, postData).then(res => {
                if (res.code == 200) {
                    this.$message({
                        message: '成功',
                        type: 'success'
                    })
                    this.geElectricityMeterData()
                } else {
                }
            }).catch(err => {

            });
        },
        /**
         * 批量新增接口
         */
        batchAddElectricityMeterData(data) {
            data.forEach(item => {
                item.isStatis = item.isStatis == '是' ? 1 : 0
            })
            let postData = [
                ...data,
            ];
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpPost(window.api.batchAddElectricityMeterData, postData).then(res => {
                if (res.code == 200 && res.data) {
                    this.$message({
                        message: '成功',
                        type: 'success'
                    })
                    this.geElectricityMeterData()
                } else {
                }
            }).catch(err => { });
        },
        /**
         * 文件上传change事件
         * @param {*} file 
         * @param {*} fileList 
         * @param {*} scope 
         */
        handleChange(file, fileList, scope) {
            let imgSize = Number(file.size / 1024 / 1024);
            if (imgSize > 5) {
                this.$message({
                    title: "",
                    message: "文件大小不能超过5MB，请重新上传。",
                    type: "warning",
                });
                this.$refs.upload.clearFiles();
                return false;
            }
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            if (response.code == 200) {
                this.$message({
                    message: response.msg,
                    type: 'success'
                })
            } else {
                this.$message({
                    message: response.msg,
                    type: 'info'
                })
            }
            this.searchTable();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
        // 关闭上传文件弹框
        closeFileForm() {
            this.upload.open = false
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
        },
        // 远程搜索数据
        async loadAll() {
            let postData = {
                pageSize: 10000,
                pageNum: 1,
            };
            let data = await this.$httpGet(window.api.getMeteringPointData, postData).then(res => {
                if (res.code == 200) {
                    return res
                }
            })
            this.restaurants = await data.rows.map(item => { return { value: item.name } })
            this.meteringPointData = data.rows
        },
        /**
         * 获取厂站
         */
        getStationTable() {
            let postData = {
                pageSize: 10000,
                pageNum: 1,
            };
            return this.$httpGet(window.api.getStationTable, postData).then(res => {
                if (res.code == 200) {
                    this.plantNameList = res.rows.map(item => {
                        return { label: item.name, value: item.id }
                    })
                    // console.log(this.plantNameList)
                }
            })
        },
        /**
         * 获取该计量点下电度量数据
         * @param {*} id 
         */
        getElecMetricData(id) {
            let postData = {
                meterId: id,
            };
            return this.$httpGet(window.api.getElecMetricData, postData).then(res => {
                if (res.code == 200) {
                    return res.data
                }
            })
        },
        /**
         * 获取指定电厂下的计量点数据/获取全部计量点数据
         */
        getMetricPointData(id) {
            let postData = {
                plantId: id,
            };
            return this.$httpGet(window.api.getMetricPointData, postData).then(res => {
                if (res.code == 200) {
                    return res.data
                }
            })
        },
    }
};
</script>
    
<style scoped lang="scss">
.electricityMeter {
    height: 100%;
}

.searchForm {
    // height: calc(100% - 40px);
    display: flex;
    // align-items: center;
    position: relative;
    flex-wrap: wrap;
    padding-right: 160px;
}

.submitForm {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}

.btnBox {
    display: flex;
    // float: right;
    z-index: 10;
    position: absolute;
    // top: 15px;
    right: 10px;
    margin: 10px 0 0 0;
}

.btnBox2 {
    display: flex;
    float: right;
    z-index: 10;
    position: absolute;
    top: 2px;
    right: 10px;
}

.upload_des {
    padding: 10px;

    ::v-deep .el-link--inner {
        font-size: 14px;
    }
}

.dialogHeaderSearch {
    background-color: var(--model-bgc);
    padding: 10px;
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
    justify-content: right;

    &.batch {
        justify-content: center;

        .dialogSearchButton {
            margin: 10px 0;
        }
    }
}

::v-deep .el-upload {
    width: 100%;

    .el-upload-dragger {
        width: auto;
    }

}

::v-deep .el-upload-list__item {
    padding: 0 14px;
}

::v-deep .el-table .el-input__inner {
    height: 28px !important;
    line-height: 28px !important;
}

.dialogHeaderSearch ::v-deep .el-table .el-table__cell {
    padding: 6px 0 !important;
}

.el-upload-dragger .el-upload__text em {
    color: rgba(72, 118, 255, 1);
}
</style>
    
    